﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using TaskClient4.SystemService;
using TaskClient4.UserService;

namespace TaskClient4
{
    public partial class MainPage
    {
        private readonly UserServiceClient _userServiceClient = new UserServiceClient();
        private readonly SystemServiceClient _systemServiceClient = new SystemServiceClient();

        public MainPage()
        {
            InitializeComponent();
            Loaded += OnMainPageLoaded;
        }

        private void OnMainPageLoaded(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                var all = _userServiceClient.GetAll();
                Dispatcher.BeginInvoke(() =>
                {
                    dataGrid1.ItemsSource = all;
                });
            });
        }

private void OnGetTimeClick(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        var time = _systemServiceClient.GetSerivceTime();
        Dispatcher.BeginInvoke(() => MessageBox.Show(time.ToString()));
    });
}

        private void OnHiClick(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                var str = _systemServiceClient.SayHiTo("Tom");
                Dispatcher.BeginInvoke(() => MessageBox.Show(str));
            });
        }

        private void OnException1Click(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                var str = _systemServiceClient.SayHiTo(null);
                Dispatcher.BeginInvoke(() => MessageBox.Show(str));
            });
        }

        private void OnException2Click(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                var num = _systemServiceClient.GetNum(0);
                Dispatcher.BeginInvoke(() => MessageBox.Show(num.ToString()));
            });
        }

        private void OnMultiTaskClick(object sender, RoutedEventArgs e)
        {
            var childWin = new TestChildWindow();
ThreadPool.QueueUserWorkItem(s =>
{
    const string format = "Num:{1},{0}{2},{0}Time:{3},{0}UserCount:{4},{0}ChildWinResult:{5}";
    var num = _systemServiceClient.GetNum(5);
    var str = _systemServiceClient.SayHiTo(num.ToString());

    var result = childWin.ShowSync();

    var time = _systemServiceClient.GetSerivceTime();
    var all = _userServiceClient.GetAll();
    var msg = string.Format(format, Environment.NewLine, num, str, time, all.Count, result);
    Dispatcher.BeginInvoke(() => MessageBox.Show(msg));
});
        }
    }
}